﻿using UnityEngine;
using UnityEngine.UI;

namespace Nomo.UnityCoreModule
{
    public static class GraphicHelper
    {
        public static void AddLine(Graphic graphic, VertexHelper vh, Vector2 from, Vector2 to, float width, Color color)
        {
            if (graphic == null)
            {
                return;
            }

            if (vh == null)
            {
                return;
            }

            if (from == to)
            {
                return;
            }

            if (width <= 0F)
            {
                return;
            }

            var angle             = Vector2.SignedAngle(to - from, graphic.rectTransform.up);
            var pixelAdjustedRect = graphic.GetPixelAdjustedRect();
            var uvOffset          = new Vector2(0.5F, 0.5F);

            var uiVertices = new UIVertex[4];
            for (var i = 0; i < 4; i++)
            {
                uiVertices[i] = UIVertex.simpleVert;
            }

            float x;
            float y;
            var   cosineAngle = Mathf.Cos(angle * Mathf.Deg2Rad);
            var   sineAngle   = Mathf.Sin(angle * Mathf.Deg2Rad);

            x                      = from.x + width * 0.5F * cosineAngle;
            y                      = from.y - width * 0.5F * sineAngle;
            uiVertices[0].color    = color * graphic.color;
            uiVertices[0].position = new Vector2(x, y);
            uiVertices[0].uv0      = new Vector2(x / pixelAdjustedRect.width, y / pixelAdjustedRect.height) + uvOffset;

            x                      = from.x - width * 0.5F * cosineAngle;
            y                      = from.y + width * 0.5F * sineAngle;
            uiVertices[1].color    = color * graphic.color;
            uiVertices[1].position = new Vector2(x, y);
            uiVertices[1].uv0      = new Vector2(x / pixelAdjustedRect.width, y / pixelAdjustedRect.height) + uvOffset;

            x                      = to.x - width * 0.5F * cosineAngle;
            y                      = to.y + width * 0.5F * sineAngle;
            uiVertices[2].color    = color * graphic.color;
            uiVertices[2].position = new Vector2(x, y);
            uiVertices[2].uv0      = new Vector2(x / pixelAdjustedRect.width, y / pixelAdjustedRect.height) + uvOffset;

            x                      = to.x + width * 0.5F * cosineAngle;
            y                      = to.y - width * 0.5F * sineAngle;
            uiVertices[3].color    = color * graphic.color;
            uiVertices[3].position = new Vector2(x, y);
            uiVertices[3].uv0      = new Vector2(x / pixelAdjustedRect.width, y / pixelAdjustedRect.height) + uvOffset;

            vh.AddUIVertexQuad(uiVertices);
        }
    }
}
